package com.hsjk.szwj.module.train.controller.admin;

import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hsjk.szwj.framework.common.pojo.CommonResult;
import com.hsjk.szwj.module.train.controller.admin.dto.QuestionInitDTO;
import com.hsjk.szwj.module.train.dal.dataobject.question.QuestionAnswerItemDO;
import com.hsjk.szwj.module.train.dal.dataobject.question.QuestionDO;
import com.hsjk.szwj.module.train.enums.QuestionStatusEnum;
import com.hsjk.szwj.module.train.service.IQuestionService;
import com.hsjk.szwj.module.train.service.IQuestionSetService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.hsjk.szwj.framework.common.pojo.CommonResult.success;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/17 00:27
 **/
@Tag(name = "管理端 - 题库相关接口")
@RestController
@RequestMapping("/train/question")
@Validated
@Slf4j
public class AdminQuestionController {

    @Resource
    private IQuestionService questionService;

    @Resource
    private IQuestionSetService questionSetService;

    @PostMapping("/init-import")
    @Operation(summary = "题库数据初始化导入")
    @PermitAll
    public CommonResult<Boolean> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        CsvReader reader = new CsvReader(convertMultipartFileToFile(file), new CsvReadConfig());
        reader.setContainsHeader(true);
        List<QuestionInitDTO> initDTOList = new ArrayList<>();
        int errorCount = 0;
        try {
            reader.stream().forEach(csvRow -> {
                System.out.println(csvRow.toString());
                String answerIndex = csvRow.get(0);
                String answerIndexJson = JSONUtil.toJsonStr(answerIndex);
                List<Integer> answerList = JSONUtil.parseArray(answerIndexJson).toList(Integer.class);
                System.out.println(answerList);
                Integer carType = Integer.valueOf(csvRow.get(1));
                String chapterInfo = csvRow.get(2);
                Integer chapterNo = Integer.valueOf(csvRow.get(3));
                List<String> knowpointCodeList = new ArrayList<>();
                String knowpointStr = csvRow.get(4);
                String mark = ".";
                if (knowpointStr.indexOf(mark) > 1) {
                    String[] split = knowpointStr.split(mark);
                    for (int i = 0; i < split.length; i++) {
                        knowpointCodeList.add(String.format("%03d", Integer.valueOf(split[i])));
                    }
                } else {
                    String knowpointCode = String.format("%03d", Integer.valueOf(knowpointStr));
                    knowpointCodeList.add(knowpointCode);
                }
                String official = csvRow.get(5);
                String options = csvRow.get(6);
                JSONObject parse = JSONUtil.parseObj(options);
                List<QuestionAnswerItemDO> itemDOS = new ArrayList<>();
                for (int i = 1; i <= parse.size(); i++) {
                    QuestionAnswerItemDO itemDO = new QuestionAnswerItemDO();
                    itemDO.setIndex(i);
                    itemDO.setAnswer(String.valueOf(parse.get(i + "")));
                    itemDOS.add(itemDO);
                }
                System.out.println(itemDOS);
                Integer quType = Integer.valueOf(csvRow.get(7));
                Integer subject = Integer.valueOf(csvRow.get(8));
                String tagIds = csvRow.get(9);
                String tagIdsJson = JSONUtil.toJsonStr(tagIds);
                List<String> tagIdsList = JSONUtil.parseArray(tagIdsJson).toList(String.class);
                System.out.println(tagIdsList);
                String title = csvRow.get(10);
                QuestionInitDTO initDTO = new QuestionInitDTO();
                QuestionDO questionDO = new QuestionDO();
                questionDO.setQuestionType(quType);
                questionDO.setQuestionAnswer(itemDOS);
                questionDO.setQuestionStatus(QuestionStatusEnum.UP.getStatus());
                questionDO.setQuestionTitle(title);
                questionDO.setQuestionOptionIndex(answerList);
                questionDO.setCarType(carType);
                questionDO.setOfficialGuide(official);
                questionDO.setSubject(subject);
                initDTO.setQuestionDO(questionDO);
                initDTO.setChapterNo(chapterNo);
                initDTO.setCarType(carType);
                initDTO.setSubject(subject);
                initDTO.setTagList(tagIdsList);
                initDTO.setKnowpointCodeList(knowpointCodeList);
                initDTOList.add(initDTO);
            });
            questionService.questionInit(initDTOList);
        } catch (Exception e) {
            errorCount++;
            log.error("init:", e);
        }
        System.out.println("errorCount:" + errorCount);
        return success(true);
    }

    @GetMapping("/init-standard-paper")
    @Operation(summary = "初始化标准考题")
    @PermitAll
    public CommonResult<Boolean> initStandardPaper() {
        questionService.initStandardPaper();
        return success(true);
    }

//    @GetMapping("/transform-space-question-set")
//    @Operation(summary = "转换地方题")
//    @PermitAll
//    public CommonResult<Boolean> transformSpaceQuestionSet() {
//        questionSetService.transformSpaceQuestionSet();
//        return success(true);
//    }

    public static File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File file = new File(multipartFile.getOriginalFilename());
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(multipartFile.getBytes());
        fileOutputStream.close();
        return file;
    }

}
